//弹窗
function confirms(content, callback) {
    return new Promise((resolve) => {
        // 创建遮罩层
        const overlay = document.createElement('div');
        overlay.className = 'v-modal';
        overlay.style.cssText = 'position: fixed; inset: 0; z-index: 2000; background-color: rgba(0,0,0,0.5);';

        // 创建对话框
        const dialog = document.createElement('div');
        dialog.className = 'el-message-box__wrapper';
        dialog.style.cssText = 'position: fixed; inset: 0; z-index: 2001; display: flex; align-items: center; justify-content: center;';
        dialog.innerHTML = `
      <div class="el-message-box">
        <div class="el-message-box__header">
          <div class="el-message-box__title"><span>系统提示</span></div>
        </div>
        <div class="el-message-box__content">
          <div class="el-message-box__message"><p>${content}</p></div>
        </div>
        <div class="el-message-box__btns">
          <button type="button" class="el-button el-button--default el-button--small cancel-btn">
            <span>取消</span>
          </button>
          <button type="button" class="el-button el-button--default el-button--small el-button--primary confirm-btn">
            <span>确认</span>
          </button>
        </div>
      </div>
    `;

        // 添加到文档
        document.body.appendChild(overlay);
        document.body.appendChild(dialog);

        // 绑定确认按钮事件
        const confirmBtn = dialog.querySelector('.confirm-btn');
        confirmBtn.addEventListener('click', () => {
            removeDialog(overlay, dialog); // 关闭弹窗
            callback(true); // 调用回调并传入结果（true=确认）
        });
        // 绑定取消按钮事件
        const cancelBtn = dialog.querySelector('.cancel-btn');
        cancelBtn.addEventListener('click', () => {
            resolve(false); // 点击取消返回 false
            removeDialog(overlay, dialog); // 关闭弹窗
        });

        // 绑定遮罩层点击事件
        overlay.addEventListener('click', () => {
            resolve(false); // 点击遮罩返回 false
            removeDialog(overlay, dialog); // 关闭弹窗
        });

        // 统一关闭弹窗函数
        function removeDialog(overlay, dialog) {
            overlay.remove();
            dialog.remove();
        }
    });
}
function showCustomAlert(message, duration) {
    let customAlert = document.getElementById('customAlert');
    if (!customAlert) {
        div_outter=document.createElement('div');
        customAlert = document.createElement('div');
        customAlert.id = 'customAlert';
        // customAlert.style.margin='7px 12px';
        const alertMessage = document.createElement('p');
        alertMessage.id = 'alertMessage';
        customAlert.appendChild(alertMessage);

        document.body.appendChild(customAlert);
    }

    const alertMessage = document.getElementById('alertMessage');

    alertMessage.textContent = message;
    if(alertMessage.textContent==null){
        customAlert.style.display = 'none';
    }

    customAlert.style.display = 'block';
    setTimeout(() => {
        customAlert.style.display = 'none';
    }, duration);
}

document.addEventListener('DOMContentLoaded', function () {
    const navLinks = document.querySelectorAll('.nav-link');
    const contentAreas = document.querySelectorAll('.content');

    // 模拟点击第一个带有 active 类的导航链接
    const activeLink = document.querySelector('.nav-link.active');
    if (activeLink) {
        const targetId = activeLink.dataset.target;
        const targetContent = document.getElementById(targetId);
        navLinks.forEach(navLink => navLink.classList.remove('active'));
        contentAreas.forEach(content => content.classList.remove('active'));
        activeLink.classList.add('active');
        if (targetContent) {
            targetContent.classList.add('active');
        }
    }

    navLinks.forEach(link => {
        link.addEventListener('click', function (e) {
            navLinks.forEach(navLink => navLink.classList.remove('active'));
            contentAreas.forEach(content => content.classList.remove('active'));
            this.classList.add('active');
            const targetId = this.dataset.target;
            const targetContent = document.getElementById(targetId);
            if (targetContent) {
                targetContent.classList.add('active');
            }
        });
    });
    const tables = document.querySelectorAll('.adminManagement-table');
    tables.forEach(function (table) {
        const selectAll = table.querySelector('.selectAll');
        const rowCheckboxes = table.querySelectorAll('.rowCheckbox');

        selectAll.addEventListener('change', function () {
            const isChecked = this.checked;
            rowCheckboxes.forEach(function (checkbox) {
                checkbox.checked = isChecked;
            });
        });

        rowCheckboxes.forEach(function (checkbox) {
            checkbox.addEventListener('change', function () {
                const allChecked = Array.from(rowCheckboxes).every(function (cb) {
                    return cb.checked;
                });
                selectAll.checked = allChecked;
            });
        });
    });
//分页
    $(document).ready(function() {

        const rowsPerPage = 4; // 每页显示的行数，需与后端默认 pageSize 一致
        const $tableBody = $('#postList');
        const $pageNav = $('#pageNav');
        let currentPage = 1;
        let totalPages = 1;


        $tableBody.on('click', '.editbtn, .deletebtn, .editbtns', function(event) {
            const $btn = $(event.target);
            const postId = $btn.data('id'); // 从data-id获取ID
            const action = $btn.hasClass('editbtn') ? '详情' :
                $btn.hasClass('deletebtn') ? '驳回' :
                    $btn.hasClass('editbtns') ? '通过' : '';

            switch (action) {
                case '详情':
                    openModalAndFillData('editModal', $btn[0]); // 打开详情模态框
                    break;
                case '驳回':
                    handlePostAction(postId, '驳回', '/admin/toRejectPost');
                    break;
                case '通过':
                    handlePostAction(postId, '通过', '/admin/toApprovePost');
                    break;
            }
        });
        // 初始化加载第一页数据
        loadPage(1);

        // 加载指定页数据
        function loadPage(pageNumber) {
            currentPage = pageNumber;
            $tableBody.html('<tr><td colspan="7" class="text-center">加载中...</td></tr>'); // 显示加载状态

            $.ajax({
                type: 'GET',
                url: '/admin/getPostsFromManagerWithPaging', // 后端分页接口
                data: {
                    pageNum: pageNumber,
                    pageSize: rowsPerPage
                },
                success: function(response) {
                    console.log('后端返回数据:', response);
                    const PostList = response.list || [];
                    const usernameList = response.usernameList || [];
                    totalPages = response.totalPage || 1;

                    $tableBody.empty();
                    if (PostList.length > 0 && usernameList.length > 0 ) {
                        PostList.forEach((post,index) => {
                            const row = $('<tr>')
                                .attr('data-id', post.id)
                                .append(`
                                <td><input type="checkbox" class="rowCheckbox" data-id="${post.id}"></td>
                                <td class="title-cell">${usernameList[index]}</td>
                                <td class="title-cell">${post.title}</td>
                                <td>${post.createdAt}</td>
                                <td>
                                    <div class="contents">${post.content}</div>
                                    <img src="${post.imageUrl || 'https://picsum.photos/200/150'}" alt="图片" style="width: 70px; height: 70px;" class="imgs">
                                </td>
                                <td>
                                    <button class="editbtn text-xl" data-id="${post.id}">详情</button>
                                    <button class="deletebtn" data-id="${post.id}">驳回</button>
                                    <button class="editbtns text-xl" data-id="${post.id}">通过</button>
                                </td>
                            `);
                            $tableBody.append(row);
                        });
                        $pageNav.show();
                    } else {
                        $pageNav.hide();
                    }

                    updatePagination();
                },
                error: function(error) {
                    console.error('分页数据加载失败:', error);
                    $tableBody.html('<tr><td colspan="7" class="text-center">加载失败，请重试</td></tr>');
                    $pageNav.hide();
                }
            });

            //查询
            $(document).ready(function() {
                const tableBody = $('#postList'); // 正确选择 tbody 的 id
                const notice = $('#notice'); // 无数据提示
                const nopost=$('#noPost');

                $('#checkkey-button').click(function() {
                    const searchTerm = $('#check').val().trim();
                    if (!searchTerm) {
                        showCustomAlert('请输入查询关键词',3000);
                        return;
                    }

                    $.ajax({
                        type: 'GET',
                        url: '/admin/behindManagerPost',
                        data: { query: searchTerm ,
                            pageNum: currentPage  },
                        success: function(response) {
                            tableBody.empty(); // 清空旧数据
                            notice.hide(); // 隐藏提示
                            nopost.hide(); // 隐藏提示
                            // 解析 HTML 响应
                            const parser = new DOMParser();
                            const doc = parser.parseFromString(response, 'text/html');

                            // 从 HTML 中提取用户行，并过滤包含关键词的行（根据帖子标题匹配）
                            const postRows = Array.from(doc.querySelectorAll('#postList tr'))
                                .filter(row => {
                                    const titleCell = row.querySelector('td:nth-child(3)'); // 帖子标题在第3列
                                    return titleCell && titleCell.textContent.toLowerCase().includes(searchTerm);
                                });

                            if (postRows.length === 0) {
                                notice.show();
                                nopost.hide();// 显示无数据提示
                                return;
                            }else{
                                notice.hide();
                            }


                            // 遍历过滤后的行并添加到表格
                            postRows.forEach(row => {
                                const postId = row.getAttribute('data-id') || row.getAttribute('th:data-id');

                                const cells = row.querySelectorAll('td');

                                // 提取单元格内容
                                const nickname = cells[1].textContent.trim(); // 昵称在第2列
                                const title = cells[2].textContent.trim(); // 标题在第3列
                                const createdAt = cells[3].textContent.trim(); // 发布时间在第4列
                                const content = cells[4].querySelector('.contents')?.textContent.trim() || '无内容'; // 内容在第5列
                                const imgElement = cells[4].querySelector('.imgs'); // 获取 img 元素
                                const imageUrl = imgElement ? imgElement.getAttribute('src') || imgElement.src : 'https://picsum.photos/200/150';
                                // 创建新行
                                const newRow = $('<tr>')
                                    .attr('data-id', postId)
                                    .append(`<td><input type="checkbox" class="rowCheckbox" data-id="${postId}"></td>`)
                                    .append(`<td>${nickname}</td>`)
                                    .append(`<td class="title-cell">${title}</td>`)
                                    .append(`<td>${createdAt}</td>`)
                                    .append(`<td>
                            <div class="contents">${content}</div>
                            <img src="${imageUrl}" alt="图片" style="width: 70px; height: 70px;">
                        </td>`)
                                    .append(`<td>
                            <button class="editbtn text-xl" data-id="${postId}">详情</button>
                            <button class="deletebtn"  data-id="${postId}">驳回</button>
                            <button class="editbtns text-xl"  data-id="${postId}">通过</button>
                        </td>`);

                                tableBody.append(newRow);
                            });
                        },
                        error: function(error) {
                            console.error('查询失败:', error);
                            showCustomAlert('查询失败，请稍后重试',3000);
                        }
                    });
                });
            });
        }

        // 更新分页导航
        function updatePagination() {
            $pageNav.empty(); // 清空原有导航

            // 上一页按钮
            const $prevBtn = $('<a href="#" class="prev-btn">').text('上一页');
            if (currentPage === 1) {
                $prevBtn.addClass('disabled'); // 第一页时禁用
            } else {
                $prevBtn.click(function(e) {
                    e.preventDefault();
                    loadPage(currentPage - 1);
                });
            }
            $pageNav.append($prevBtn);

            // 页码按钮（显示当前页附近的页码）
            const maxVisiblePages = 5;
            let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
            let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);

            // 左侧省略号
            if (startPage > 1) {
                $pageNav.append($('<span>').text('...'));
            }

            // 页码按钮
            for (let i = startPage; i <= endPage; i++) {
                const $pageBtn = $('<a href="#" class="num">').text(i);
                if (i === currentPage) {
                    $pageBtn.addClass('active'); // 高亮当前页
                } else {
                    $pageBtn.click(function(e) {
                        e.preventDefault();
                        loadPage(i);
                    });
                }
                $pageNav.append($pageBtn);
            }

            // 右侧省略号
            if (endPage < totalPages) {
                $pageNav.append($('<span>').text('...'));
            }

            // 下一页按钮
            const $nextBtn = $('<a href="#" class="next-btn">').text('下一页');
            if (currentPage === totalPages) {
                $nextBtn.addClass('disabled'); // 最后一页时禁用
            } else {
                $nextBtn.click(function(e) {
                    e.preventDefault();
                    loadPage(currentPage + 1);
                });
            }
            $pageNav.append($nextBtn);
        }
    });
// 返回表单
    const backform = document.getElementById('backform');
    backform.addEventListener('click', function () {
        location.reload();
    });


    const namePostTitle = document.getElementById('namePostTitle');
    const editPostTitleInput = document.getElementById('editPostTitle');
    const editPostContentDiv = document.getElementById('editPostContentDivs');
    let currentEditRow;

// 封装：打开模态框并填充数据
    function openModalAndFillData(modalId, button) {
        const modal = document.getElementById(modalId);
        if (!modal) return; // 确保模态框存在

        modal.style.display = 'block';
        const currentRow = button.closest('tr'); // 获取当前行
        currentEditRow = currentRow; // 保存当前行到全局变量

        if (!currentRow) return; // 确保行存在

        // 提取并处理数据
        const name = currentRow.querySelector('td:nth-child(2)').textContent;
        const title = currentRow.querySelector('td:nth-child(3)').textContent;
        const fullContentCell = currentRow.querySelector('td:nth-child(5)');
        let fullContent = fullContentCell?.innerHTML || ''; // 安全获取innerHTML

        // 去除.contents类
        const tempDiv = document.createElement('div');
        tempDiv.innerHTML = fullContent;
        const contentsDiv = tempDiv.querySelector('.contents');
        if (contentsDiv) {
            contentsDiv.classList.remove('contents');
        }
        fullContent = tempDiv.innerHTML;

        // 填充表单
        namePostTitle.value = name;
        editPostTitleInput.value = title;
        editPostContentDiv.innerHTML = fullContent;
    }

    //驳回和通过
    // 通过按钮
    document.querySelectorAll('.editbtns.text-xl:last-child').forEach(button => {
        button.addEventListener('click', function() {
            const postId = this.getAttribute('data-id');
            handlePostAction(postId, '通过', '/admin/toApprovePost');
        });
    });

    // 驳回按钮
    document.querySelectorAll('.deletebtn').forEach(button => {
        button.addEventListener('click', function() {
            const postId = this.getAttribute('data-id');
            handlePostAction(postId, '驳回', '/admin/toRejectPost');
        });
    });

    // 全选/取消全选功能
    $('.selectAll').change(function() {
        $('.rowCheckbox').prop('checked', this.checked);
        updateButtonState();
    });

    // 单个复选框变化时更新按钮状态
    $('.rowCheckbox').change(updateButtonState);

    // 更新按钮状态
    function updateButtonState() {
        const hasChecked = $('.rowCheckbox:checked').length > 0;
        $('#check-button, #pass-button').prop('disabled', !hasChecked);
    }

    // 批量驳回按钮
    $('#check-button').click(function() {
        const checkedIds = getCheckedIds();
        if (!checkedIds.length) return;
        confirms(`确定要驳回选中的 ${checkedIds.length} 个帖子吗？`, (isConfirmed) => {
            if (isConfirmed) {
            processBatchAction(checkedIds, '驳回', '/admin/toRejectPost');
        }
    });
    });
    // 批量通过按钮
    $('#pass-button').click(function() {
        const checkedIds = getCheckedIds();
        if (!checkedIds.length) return;
        confirms(`确定要通过选中的 ${checkedIds.length} 个帖子吗？`, (isConfirmed) => {
            if (isConfirmed) {
            processBatchAction(checkedIds, '通过', '/admin/toApprovePost');
        }
    });
    });
    // 获取选中的帖子ID
    function getCheckedIds() {
        return $('.rowCheckbox:checked').map(function() {
            return $(this).attr('data-id');
        }).get();
    }

    // 批量处理函数（循环调用单个接口）
    function processBatchAction(ids, actionText, apiUrl) {
        let successCount = 0;
        let failedCount = 0;
        let currentIndex = 0;

        // 禁用按钮防止重复点击
        $('#check-button, #pass-button').prop('disabled', true);

        function processNext() {
            if (currentIndex >= ids.length) {
                // 全部处理完成
                let message = successCount > 0
                    ? `${actionText}成功 ${successCount} 个帖子`
                    : '没有帖子被处理';

                if (failedCount > 0) {
                    message += `，${failedCount} 个处理失败`;
                }

                alert(message);
                location.reload(); // 刷新页面
                return;
            }

            const postId = ids[currentIndex];
            $.ajax({
                url: `${apiUrl}?id=${postId}`,
                type: 'GET',
                success: function() {
                    successCount++;
                    currentIndex++;
                    processNext();
                },
                error: function() {
                    failedCount++;
                    currentIndex++;
                    console.error(`${actionText}失败，ID: ${postId}`);
                    processNext(); // 继续处理下一个
                }
            });
        }

        // 开始处理第一个
        processNext();
    }

    function handlePostAction(postId, actionText, apiUrl) {
        confirms(`确定要${actionText}这个帖子吗？`, (isConfirmed) => {
            if (isConfirmed) {
                $.ajax({
                    url: `${apiUrl}?id=${postId}`,
                    type: 'GET',
                    success: function (response) {
                        showCustomAlert(`${actionText}成功`, 3000);
                        location.reload();
                    },
                    error: function (error) {
                        console.error(`${actionText}失败`, error);
                        showCustomAlert(`${actionText}失败，请稍后再试`, 3000);
                    }
                });
            }
        });
    }


    const modals = ['editModal', 'userEditModal', 'commentEditModal', 'categoryEditModal', 'reportEditModal'];
    modals.forEach(function (modalId) {
        const modal = document.getElementById(modalId);
        if (modal) {
            modal.style.display = 'none';
        }
    });
});

// 为所有取消按钮添加点击事件
const cancelEditPostButtons = document.querySelectorAll('.cancelEditPost');
cancelEditPostButtons.forEach(function (cancelEditPostButton) {
    cancelEditPostButton.addEventListener('click', function () {
        const modals = ['editModal', 'userEditModal', 'commentEditModal', 'categoryEditModal', 'reportEditModal'];
        modals.forEach(function (modalId) {
            const modal = document.getElementById(modalId);
            if (modal) {
                modal.style.display = 'none';
            }
        });
    });
    //添加

    // 获取DOM元素
    const addButton1 = document.getElementById('addButton1');
    const addModal = document.getElementById('addModal');
    const saveButton = document.querySelector('.saveEditPost');
    const cancelButton = document.querySelector('.cancelEditPost0');
    const nameInput = document.getElementById('namePostTitle1');
    const titleInput = document.getElementById('editPostTitle1');
    const contentDiv = document.getElementById('editPostContentDiv');

// 打开模态框
    addButton1.addEventListener('click', function() {
        addModal.style.display = 'block';
        // 清空之前的输入
        nameInput.value = '';
        titleInput.value = '';
        contentDiv.textContent = '';
    });

// 关闭模态框
    cancelButton.addEventListener('click', function() {
        addModal.style.display = 'none';
    });

// 点击模态框外部关闭
    window.addEventListener('click', function(event) {
        if (event.target === addModal) {
            addModal.style.display = 'none';
        }
    });

// 保存按钮点击事件 - 使用 jQuery AJAX
    saveButton.addEventListener('click', function() {
        // 表单验证
        if (!validateForm()) {
            return;
        }

        // 收集表单数据
        const formData = {
            nickname: nameInput.value.trim(),
            title: titleInput.value.trim(),
            content: contentDiv.textContent.trim()
        };

        // 显示加载状态
        showLoading(true);

        // 使用 jQuery AJAX 发送请求
        $.ajax({
            url: '/addPost',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(formData),
            success: function(response) {
                showLoading(false);

                if (response.success) {
                    showNotification('添加成功', true);
                    addModal.style.display = 'none';
                } else {
                    showNotification(response.message || '添加失败', false);
                }
            },
            error: function(xhr, status, error) {
                showLoading(false);
                showNotification('服务器错误: ' + xhr.status, false);
            }
        });
    });

// 表单验证函数
    function validateForm() {
        if (!nameInput.value.trim()) {
            showNotification('请输入昵称', false);
            nameInput.focus();
            return false;
        }

        if (!titleInput.value.trim()) {
            showNotification('请输入标题', false);
            titleInput.focus();
            return false;
        }

        if (titleInput.value.length > 10) {
            showNotification('标题长度不能超过10个字符', false);
            titleInput.focus();
            return false;
        }

        if (!contentDiv.textContent.trim()) {
            showNotification('请输入内容', false);
            contentDiv.focus();
            return false;
        }

        return true;
    }

// 显示通知函数
    function showNotification(message, isSuccess) {
        const notification = document.createElement('div');
        notification.className = isSuccess ? 'notification success' : 'notification error';
        notification.textContent = message;
        document.body.appendChild(notification);

        // 添加动画类
        setTimeout(() => {
            notification.classList.add('show');
        }, 10);

        // 3秒后移除通知
        setTimeout(() => {
            notification.classList.remove('show');
            setTimeout(() => {
                document.body.removeChild(notification);
            }, 300);
        }, 3000);
    }

// 显示/隐藏加载状态
    function showLoading(isLoading) {
        if (isLoading) {
            saveButton.disabled = true;
            saveButton.textContent = '保存中...';
        } else {
            saveButton.disabled = false;
            saveButton.textContent = '保存';
        }
    }
    // 为取消按钮添加点击事件监听器
});